package com.molichuxing.services.infrastructure.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.molichuxing.services.infrastructure.bean.RegionBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.RegionMapper;
import com.molichuxing.services.infrastructure.dto.response.RegionCityDto;
import com.molichuxing.services.infrastructure.dto.response.RegionDto;
import com.molichuxing.services.infrastructure.dto.response.RegionInfoDto;
import com.molichuxing.services.infrastructure.service.RegionService;

/**
 * <p>
 * 行政区域 服务实现类
 * </p>
 *
 * @author zoumingyu
 * @since 2019-07-28
 */
@Service("regionService")
public class RegionServiceImpl implements RegionService {
	private static final Logger logger = LoggerFactory.getLogger(RegionServiceImpl.class);

	@Resource
	private RegionMapper regionMapper;

	/**
	 * 获取所有省市区信息
	 * 
	 * @return
	 */
	@Override
	public List<RegionDto> getAll() {
		logger.info("[getAll]获取所有省市区信息");
		List<RegionBean> dictList = regionMapper.getAll();
		// 转换返回
		return Convert.toRegionBeanDto(dictList);
	}

	@Override
	public List<RegionCityDto> getAllCity(Integer level) {
		List<RegionBean> regionBeans = regionMapper.getAll();
		List<RegionCityDto> provincs = getRegion(regionBeans, 0);
		if (null != level && level == 1) {
			return provincs;
		}
		for (RegionCityDto province : provincs) {
			List<RegionCityDto> provinceCitys = getRegion(regionBeans, province.getId());
			if (provinceCitys.size() == 0) {
				RegionCityDto regionCityDto = new RegionCityDto();
				regionCityDto.setId(null);
				regionCityDto.setPid(null);
				regionCityDto.setName("");
				provinceCitys.add(regionCityDto);
			}
			if (null != level && level == 3) {
				for (RegionCityDto provinceCity : provinceCitys) {
					List<RegionCityDto> areas = getRegion(regionBeans, provinceCity.getId());
					if (areas.size() == 0) {
						RegionCityDto area = new RegionCityDto();
						area.setId(null);
						area.setPid(null);
						area.setName("");
						areas.add(area);
					}
					provinceCity.setCitys(areas);
				}
			}
			province.setCitys(provinceCitys);
		}
		return provincs;
	}





	@Override
	public List<RegionCityDto> getAllCityByRegionId(Integer level, List<Integer> regionIdList) {
		List<RegionBean> regionBeans = regionMapper.getAll();
		List<RegionCityDto> provincs = getRegion(regionBeans, 0);
		if (null != level && level == 1) {
			return provincs;
		}
		for (RegionCityDto province : provincs) {
			List<RegionCityDto> provinceCitys = getRegion(regionBeans, province.getId());
			if (provinceCitys.size() == 0) {
				RegionCityDto regionCityDto = new RegionCityDto();
				regionCityDto.setId(null);
				regionCityDto.setPid(null);
				regionCityDto.setName("");
				provinceCitys.add(regionCityDto);
			}
			if (null != level && level == 3) {
				for (RegionCityDto provinceCity : provinceCitys) {
					List<RegionCityDto> areas = getRegion(regionBeans, provinceCity.getId());
					if (areas.size() == 0) {
						RegionCityDto area = new RegionCityDto();
						area.setId(null);
						area.setPid(null);
						area.setName("");
						areas.add(area);
					}
					provinceCity.setCitys(areas);
				}
			}
			province.setCitys(provinceCitys);
		}
		if((null != regionIdList)&&(regionIdList.size() > 0)) {
			List<RegionCityDto> result = null;
			List<RegionInfoDto> areaDataList = getProvincesByCityIds(regionIdList);
			if((null != areaDataList)&&(areaDataList.size() > 0)) {
				result = new ArrayList<>();
				//移除省
				Iterator<RegionCityDto> iterator = provincs.iterator();
				while(iterator.hasNext()){
					RegionCityDto regionCityDtoIterator = iterator.next();
					for(RegionInfoDto regionInfoDto : areaDataList) {
						if(regionCityDtoIterator.getId().equals(regionInfoDto.getProvinceId())){
							result.add(regionCityDtoIterator);
							break;
						}
					}
				}
				//移除市
				for(RegionCityDto regionCityDto: result) {
					List<RegionCityDto> citys = regionCityDto.getCitys();
					Iterator<RegionCityDto> resultIterator = citys.iterator();
					while(resultIterator.hasNext()){
						if(!regionIdList.contains(resultIterator.next().getId())){
							resultIterator.remove();
						}
					}
				}
			}
			return result;
		}else {
			return provincs;
		}
	}



	private List<RegionCityDto> getRegion(List<RegionBean> citys, Integer parentId) {
		List<RegionCityDto> list = new ArrayList<RegionCityDto>();
		for (RegionBean regionBean : citys) {
			if (regionBean.getPid().equals(parentId)) {
				if (0 != regionBean.getId()) {
					RegionCityDto dto = new RegionCityDto();
					dto.setId(regionBean.getId());
					dto.setName(regionBean.getName());
					dto.setPid(regionBean.getPid());
					list.add(dto);
				}
			}
		}
		return list;
	}

	@Override
	// 根据省id获取省下所有的市 市下所有的区县
	public List<RegionDto> getCityListByProvinceId(Integer provinceId) {
		List<RegionDto> dto = null;
		if (provinceId == null) {
			List<RegionBean> regionBeanList = regionMapper.getAllProvince();
			if (regionBeanList != null && regionBeanList.size() > 0) {
				dto = new ArrayList<RegionDto>();
				for (RegionBean regionBean : regionBeanList) {
					RegionDto regionDto = new RegionDto();
					BeanUtils.copyProperties(regionBean, regionDto);
					dto.add(regionDto);
				}
			}
			return dto;
		}
		RegionBean region = regionMapper.getById(provinceId);
		if (region == null) {
			return dto;
		}

		List<RegionBean> regionBeanList = regionMapper.getByPid(region.getId());
		if (regionBeanList != null && regionBeanList.size() > 0) {
			dto = new ArrayList<RegionDto>();
			for (RegionBean regionBean : regionBeanList) {
				RegionDto regionDto = new RegionDto();
				BeanUtils.copyProperties(regionBean, regionDto);
				dto.add(regionDto);
			}
		}

		return dto;
	}

	@Override
	public List<RegionDto> getAreaListByProvinceId(Integer provinceId) {
		List<RegionDto> result = new ArrayList<>();
		List<RegionBean> regionBeanList = regionMapper.getByPid(provinceId);
		if (null == regionBeanList || regionBeanList.size() == 0) {
			return null;
		}
		for (RegionBean regionBean : regionBeanList) {
			regionBeanList = regionMapper.getByPid(regionBean.getId());
			for (RegionBean bean : regionBeanList) {
				RegionDto regionDto = new RegionDto();
				BeanUtils.copyProperties(bean, regionDto);
				result.add(regionDto);
			}
		}
		return result;
	}

	@Override
	public RegionInfoDto getCityNameByAreaId(Integer areaId) {
		RegionInfoDto dto = null;
		if (areaId == null) {
			return dto;
		}
		// 区
		RegionBean area = regionMapper.getById(areaId);
		if (area == null) {
			return dto;
		}
		dto = new RegionInfoDto();
		dto.setAreaId(area.getId());
		dto.setAreaName(area.getShortName());
		dto.setAreaFullName(area.getFullName());
		// 根据区id查询市
		RegionBean city = regionMapper.getById(area.getPid());
		if (city == null) {
			return dto;
		}
		dto.setCityId(city.getId());
		dto.setCityName(city.getShortName());
		dto.setCityFullName(city.getFullName());
		// 根据市id查询省
		RegionBean province = regionMapper.getById(city.getPid());
		if (province == null) {
			return dto;
		}
		dto.setProvinceId(province.getId());
		dto.setProvinceName(province.getShortName());
		dto.setProvinceFullName(province.getFullName());
		return dto;
	}

	@Override
	public List<RegionInfoDto> getCityNameByAreaIds(List<Integer> areaIds) {
		if ((null == areaIds) || (areaIds.size() == 0)) {
			return null;
		}
		List<RegionInfoDto> result = new ArrayList<>();
		for (Integer areaId : areaIds) {
			RegionInfoDto dto = null;
			if (areaId == null) {
				continue;
			}
			// 区
			RegionBean area = regionMapper.getById(areaId);
			if (area == null) {
				continue;
			}
			dto = new RegionInfoDto();
			dto.setAreaId(area.getId());
			dto.setAreaName(area.getShortName());
			dto.setAreaFullName(area.getFullName());
			// 根据区id查询市
			RegionBean city = regionMapper.getById(area.getPid());
			if (city == null) {
				continue;
			}
			dto.setCityId(city.getId());
			dto.setCityName(city.getShortName());
			dto.setCityFullName(city.getFullName());
			// 根据市id查询省
			RegionBean province = regionMapper.getById(city.getPid());
			if (province == null) {
				continue;
			}
			dto.setProvinceId(province.getId());
			dto.setProvinceName(province.getShortName());
			dto.setProvinceFullName(province.getFullName());
			result.add(dto);
		}
		return result;
	}

	@Override
	public RegionInfoDto getCityNameByCityId(Integer cityId) {
		RegionInfoDto dto = null;
		if (cityId == null) {
			return dto;
		}
		// 根据市id查询市
		RegionBean city = regionMapper.getById(cityId);
		if (city == null) {
			return dto;
		}
		dto = new RegionInfoDto();
		dto.setCityId(city.getId());
		dto.setCityName(city.getShortName());
		dto.setCityFullName(city.getFullName());
		// 根据市id查询省
		RegionBean province = regionMapper.getById(city.getPid());
		if (province == null) {
			return dto;
		}
		dto.setProvinceId(province.getId());
		dto.setProvinceName(province.getShortName());
		dto.setProvinceFullName(province.getFullName());
		return dto;
	}

	@Override
	public Map<Integer, RegionInfoDto> getRegionInfoListByIds(List<Integer> cityIds) {
		Map<Integer, RegionInfoDto> dtoMap = new HashMap<>();
		if (cityIds != null && !cityIds.isEmpty()) {
			List<RegionBean> dtoList = regionMapper.getByIds(cityIds);
			if (dtoList != null && !dtoList.isEmpty()) {
				for (RegionBean city : dtoList) {
					RegionInfoDto dto = new RegionInfoDto();
					dto.setCityId(city.getId());
					dto.setCityName(city.getShortName());
					dto.setCityFullName(city.getFullName());
					RegionBean province = regionMapper.getById(city.getPid());
					if (province == null) {
						dtoMap.put(city.getId(), dto);
						continue;
					}
					dto.setProvinceId(province.getId());
					dto.setProvinceName(province.getShortName());
					dto.setProvinceFullName(province.getFullName());
					dtoMap.put(city.getId(), dto);
				}
			}
		}
		return dtoMap;
	}

	/**
	 * 根据市id查询省信息
	 * 
	 * @param cityIds
	 *            市id
	 * @return
	 */
	@Override
	public List<RegionInfoDto> getProvincesByCityIds(List<Integer> cityIds) {
		List<RegionInfoDto> result = null;
		if (cityIds == null || cityIds.isEmpty()) {
			return result;
		}
		// 根据市id获取省id
		List<Integer> provinceIds = regionMapper.getPidsByIds(cityIds);
		if (provinceIds == null || provinceIds.isEmpty() || provinceIds.get(0) == 0) {
			return result;
		}

		// 查询省信息
		List<RegionBean> regionBeans = regionMapper.getByIds(provinceIds);
		if (regionBeans == null || regionBeans.isEmpty()) {
			return result;
		}

		return Convert.toProvinceDto(regionBeans);
	}

	/**
	 * 根据省id查询所有省下市id
	 * 
	 * @param provinceId
	 *            省id
	 * @return
	 */
	@Override
	public List<Integer> getCityIdsByProvinceId(Integer provinceId) {
		return regionMapper.getIdsByPid(provinceId);
	}

	@Override
	public RegionDto getCityByBaiduCode(String baiduCode) {
		return Convert.toRegionBeanDto(regionMapper.getCityByBaiduCode(baiduCode));
	}

	@Override
	public Map<String, List<RegionDto>> getCityByInitial(List<Integer> regionIds) {
		if(null == regionIds||regionIds.size() ==0) {
			return null;
		}
		List<RegionBean> result = regionMapper.getCityByInitial(regionIds);
		if(null == result||result.size() ==0) {
			return null;
		}
		return Convert.toRegionBeanDto(result).stream().collect(Collectors.groupingBy(RegionDto::getInitial, LinkedHashMap::new, Collectors.toList()));
	}

}
